package com.itheima.myreggie2.service.Impl;

import ch.qos.logback.core.html.IThrowableRenderer;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.myreggie2.common.ApplicationContext;
import com.itheima.myreggie2.common.excetion.CustomException;
import com.itheima.myreggie2.dao.OrderDao;
import com.itheima.myreggie2.entity.*;
import com.itheima.myreggie2.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl extends
        ServiceImpl<OrderDao, Orders> implements IOrderService {

    @Autowired
    IShoppingCartService shoppingCartService;

    @Autowired
    IUserService userService;

    @Autowired
    IAddressBookService addressBookService;

    @Autowired
    IOrderDetailService orderDetailService;


    @Override
    public void submit(Orders orders) {

//        1. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = ApplicationContext.getId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        //调用购物车业务层的列表方法（注入购物车）
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if (shoppingCarts==null || shoppingCarts.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }
        // 2、根据当前登录用户id,查询用户数据   select * from user where id = ?
              //注入userService
        User user = userService.getById(userId);

//        3. 根据地址ID, 查询地址数据，select * from address_book where id = ?
        Long addressBookId = orders.getAddressBookId();
             //注入addressBookService
        AddressBook addressBookData = addressBookService.getById(addressBookId);
        if (addressBookData ==null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //订单号 id
        long orderId = IdWorker.getId();

        //购物车 总价格
        BigDecimal amount = new BigDecimal(0);//总价

        // 4.保存订单明细数据：点了哪些菜品或套餐

        //遍历购物车列表，构建新的订单明细详情对象，添加订单详情表
        for (ShoppingCart shoppingCart : shoppingCarts) {
            // ShoppingCart shoppingCart --> OrderDetail orderDetail
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);

            // orderId单独设置
            orderDetail.setOrderId(orderId);
            // amount 金额单独设置  数量  *  单价
            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount.add(orderDetail.getAmount());
            //插入一条订单详情   (需要注入OrderDetailService)
            orderDetailService.save(orderDetail);


        }
//        5. 保存/组装订单数据, 批量保存订单数据
        orders.setId(orderId);//订单id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//订单状态：1.待付款  2.待派送  3.已派送  4.已完成  5.已取消
        orders.setAmount(amount);//总金额
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户姓名
        orders.setConsignee(addressBookData.getPhone());//收货人联系电话


        // 保存用户  省+市+区域+详细地址
        orders.setAddress(
                (addressBookData.getProvinceName() == null ? "": addressBookData.getProvinceName())
                + (addressBookData.getCityName() == null ? "" : addressBookData.getCityName())
                +(addressBookData.getDistrictName() == null ? "" : addressBookData.getDistrictName())
                +(addressBookData.getDetail() == null ? "" : addressBookData.getDetail()));

//        6. 清空购物车数据，删除当前用户的购物车列表数据
        //创建条件构造器对象
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();

        //delete from shopping_cart where user_id =?
        queryWrapper.eq(ShoppingCart::getUserId,userId);

        //清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }
}
